package org.gdkm.interceptor;

import org.apache.commons.lang.StringUtils;
import org.gdkm.domin.TbUser;
import org.gdkm.json.MapperUtils;
import org.gdkm.service.RedisService;
import org.gdkm.util.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class WebAdminInterceptor implements HandlerInterceptor {

    @Autowired
    RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = CookieUtils.getCookieValue(request, "token");
        if (StringUtils.isBlank(token)) {
            response.sendRedirect("http://localhost:8503/login?url=http://localhost:8501/index");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HttpSession session = request.getSession();
        TbUser tbUser = (TbUser) session.getAttribute("tbUser");
        if (tbUser != null) {
            if (modelAndView != null) {
                modelAndView.addObject("tbUser", tbUser);
            }
        } else {
            String token = CookieUtils.getCookieValue(request, "token");
            if (StringUtils.isNotBlank(token)) {
                String username = redisService.get(token);
                if (StringUtils.isNotBlank(username)) {
                    String json = redisService.get(username);
                    if (StringUtils.isNotBlank(json)) {
                        tbUser = MapperUtils.json2pojo(json, TbUser.class);
                        if (modelAndView != null) {
                            modelAndView.addObject("tbUser", tbUser);
                        }
                        request.getSession().setAttribute("tbUser", tbUser);
                    }
                }
            }
        }
        if (tbUser == null) {
            response.sendRedirect("http://localhost:8503/login?url=http://localhost:8501/index");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
